package com.esl.coordinator.test.socketserver;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import javax.xml.bind.DatatypeConverter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.esl.coordinator.util.Hex;

public class SimpleHandler implements Runnable {
	static final Logger LOG = LoggerFactory.getLogger(SimpleHandler.class);

	private Socket sock = null;
	private InputStream sockInput = null;
	private OutputStream sockOutput = null;
	private Thread myThread = null;

	public SimpleHandler(Socket sock) throws IOException {
		this.sock = sock;
		sockInput = sock.getInputStream();
		sockOutput = sock.getOutputStream();
		this.myThread = new Thread(this);
		// Note that if we call myThread.start() now, we run the risk
		// of this new thread calling run before we're finished
		// constructing. We can't count on the fact that we call
		// .start() last - javac or the jvm might have reordered the
		// above lines. The class constructing us must wait for the
		// constructor to return and then call start() on us.
		LOG.info("SimpleHandler: New handler created.");
	}

	public void start() {
		myThread.start();
	}

	// All this method does is wait for some bytes from the
	// connection, read them, then write a response back, until the
	// socket is closed from the other side.
	public void run() {
		LOG.info("SimpleHandler: Handler run() starting.");

		while (true) {
			byte[] buf = new byte[128];
			int bytes_read = 0;
			try {
				// This call to read() will wait forever, until the
				// program on the other side either sends some data,
				// or closes the socket.
				bytes_read = sockInput.read(buf, 0, buf.length);
				if (bytes_read < 0) {
					break;
				}
				LOG.info("SimpleHandler: Received msg = "
						+ Hex.toHexString(buf));

				sockOutput.write(Hex.toHexBytes("CC02FFFF00000000000000"));
				// sockOutput.write(Hex.toHexBytes("0000000000000000000000"));
				LOG.info("SimpleHandler: Responded "
						+ Hex.toHexString(DatatypeConverter
								.parseHexBinary("CC02FFFF00000000000000")));
				// This call to flush() is optional - we're saying go
				// ahead and send the data now instead of buffering
				// it.
				sockOutput.flush();
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
				break;
			}
		}

		try {
			LOG.info("SimpleHandler: Closing socket.");
			sockInput.close();
			sockOutput.close();
			sock.close();
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}

	}
}
